<script setup lang="ts">
import {onMounted} from "vue";
import {userStore} from "./store/user.ts";
import router from "./router";
import ACCESS_ENUM from "./access/accessEnum.ts";
import checkAccess from "./access/checkAccess.ts";

const store = userStore();

// @ts-ignore
onMounted(() => {
    router.beforeEach(async (to, from, next) => {
        console.log("登陆用户信息", store.loginUser);
        const loginUser = store.loginUser;
        // // 如果之前没登陆过，自动登录
        if (!loginUser || !loginUser.userRole) {
            // 加 await 是为了等用户登录成功之后，再执行后续的代码
            await store.updateLoginUser();
        }
        const needAccess = (to.meta?.access as string) ?? ACCESS_ENUM.NOT_LOGIN;
        // 要跳转的页面必须要登陆
        if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
            // 如果没登陆，跳转到登录页面
            if (!loginUser || !loginUser.userRole) {
                next(`/login?redirect=${to.fullPath}`);
                return;
            }
            // 如果已经登陆了，但是权限不足，那么跳转到无权限页面
            if (!checkAccess(loginUser, needAccess)) {
                next("/noAuth");
                return;
            }
        }
        next();
    });
})
</script>

<template>
    <div>
        <router-link style="border: 1px solid black" to="/home">首页</router-link>
        <router-link style="border: 1px solid deepskyblue" to="/about">关于</router-link>
    </div>

    <div>
        <router-view></router-view>
    </div>

</template>

<style scoped>

</style>
